package com.headhunter.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.rmi.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.headhunter.rmi.GraduateImpl;
import com.headhunter.server.Graduate;
import com.headhunter.server.Headhunter;

/**
 * Servlet implementation class MainServlet
 */
@WebServlet("/MainServlet")
public class MainServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	PrintWriter pw = response.getWriter();
	pw.println("Hello from main servlet (get)");
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	PrintWriter pw = response.getWriter();
	List<String> results = new ArrayList<String>();

	try {
	    String name = request.getParameter("name");
	    String gender = request.getParameter("gender");

	    if (StringUtils.isBlank(name)) {
		pw.println("Please enter your name");
		return;
	    }

	    if (StringUtils.isBlank(gender)) {
		pw.println("Please select your gender");
		return;
	    }

	    int age = Integer.parseInt(request.getParameter("age"));

	    GraduateImpl graduate = new GraduateImpl(name, gender, age);
	    graduate.setDegrees(Arrays.asList(request.getParameterValues("degree")));
	    graduate.setQualifications(Arrays.asList(request.getParameterValues("qualification")));

	    String url = "rmi://localhost:1099/Headhunter";
	    Headhunter headHunter = (Headhunter) Naming.lookup(url);
	    results = Arrays.asList(headHunter.checkJobs(graduate).split("\\n"));
	} catch (NumberFormatException e) {
	    results.add("Age must be an integer");
	} catch (NullPointerException e){
	    results.add("Please select your degree or qualification");
	} catch (Exception e) {
	    e.printStackTrace();
	    results.add("Company server(s) unavailable");
	}
	
	request.setAttribute("results_list", results);
	request.getRequestDispatcher("result.jsp").forward(request, response);
    }

}